package cn.itcast.service.impl;

import cn.itcast.dao.ProvinceDao;
import cn.itcast.domain.Province;
import cn.itcast.service.ProvinceService;
import cn.itcast.utils.JedisUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.util.StringUtil;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import redis.clients.jedis.Jedis;

import java.util.List;

public class ProvinceServiceImpl implements ProvinceService {
    @Override
    public List<Province> findAll() throws Exception {
        Jedis jedis = JedisUtils.getJedis();
        String province = jedis.get("province");

        if (StringUtil.isEmpty(province)) {

            SqlSession sqlSession = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("MyBatisConfig.xml")).openSession();
            ProvinceDao provinceDao = sqlSession.getMapper(ProvinceDao.class);
            List<Province> list = provinceDao.findAll();

            String all = new ObjectMapper().writeValueAsString(list);
            jedis.set("province", all);
            JedisUtils.close(jedis);
            return list;

        }else {
            List list = new ObjectMapper().readValue(province, List.class);
            JedisUtils.close(jedis);
            return list;
        }


    }
}
